<template>
	<uni-popup ref="popup" :is-mask-click="false" type="bottom" style="z-index:999;">
		<view class="flex-col w-full" style="margin: 0 auto;">
			<view class="mb-12 flex justify-end">
				<image class="size-26" src="@/static/svg/icon-close.svg" @click.stop="onClose"></image>
			</view>
			<view class="radius-12 flex-col bg-white px-16 py-24">
				<view class="text-color-regular fs-14 font-semibold">导出订单</view>
				<view class="flex flex-wrap mt-20">
					<view
						class="radius-8 h-44 bg-default inline-flex center fs-14 text-color-regular mr-12 mb-12"
						style="width:102px;"
						:style="queryParam.type === 1 ? 'background:#FFEEEE;border:1px solid #FA4543;color:#FA4543;': ''"
						@click="changeType(1)"
					>近一个月</view>
					<view
						class="radius-8 h-44 bg-default inline-flex center fs-14 text-color-regular mr-12 mb-12"
						style="width:102px;"
						:style="queryParam.type === 2 ? 'background:#FFEEEE;border:1px solid #FA4543;color:#FA4543;': ''"
						@click="changeType(2)"
					>今日</view>
					<view
						class="radius-8 h-44 bg-default inline-flex center fs-14 text-color-regular mr-12 mb-12"
						style="width:102px;"
						:style="queryParam.type === 3 ? 'background:#FFEEEE;border:1px solid #FA4543;color:#FA4543;': ''"
						@click="changeType(3)"
					>昨日</view>
					<view
						class="radius-8 h-44 bg-default inline-flex center fs-14 text-color-regular mr-12 mb-12"
						style="width:102px;"
						:style="queryParam.type === 4 ? 'background:#FFEEEE;border:1px solid #FA4543;color:#FA4543;': ''"
						@click="changeType(4)"
					>本周</view>
				</view>
				<view class="my-20 text-color-regular fs-14">自定义时间</view>
				<view class="flex item-center">
					<uni-datetime-picker
						type="datetime"
						:value="queryParam.orderTimeStart"
						@change="change($event, 'start')"
					>
						<view
							class="radius-8 h-44 w-full bg-default inline-flex center"
							:style="queryParam.type === 5 && queryParam.orderTimeStart ? 'color:#333333;' : ''"
						>
							{{ queryParam.orderTimeStart ? queryParam.orderTimeStart : '开始时间' }}
						</view>
					</uni-datetime-picker>
					<view class="w-8 h-1 bg-black mx-6"></view>
					<uni-datetime-picker
						type="datetime"
						:value="queryParam.orderTimeEnd"
						@change="change($event, 'end')"
					>
						<view
							class="radius-8 h-44 w-full bg-default flex-1 inline-flex center"
							:style="queryParam.type === 5 && queryParam.orderTimeEnd ? 'color:#333333;' : ''"
						>
							{{ queryParam.orderTimeEnd ? queryParam.orderTimeEnd : '结束时间' }}
						</view>
					</uni-datetime-picker>
				</view>
				<view class="mt-40">
					<button class="bg-primary radius-8 h-46 mx-16 text-white fs-16 font-semibold" @click="query">确定</button>
				</view>
			</view>
		</view>
	</uni-popup>
</template>

<script setup name="ExportPopup">
	import dayjs from 'dayjs'
	import { ref, unref } from 'vue'
	import { preExportApi, exportOrderUrl } from '@/api/order.js'
	
	const props = defineProps({
		id: {
			type: [Number, String]
		}
	})
	
	const popup = ref(null)
	
	const onClose = () => {
		popup.value && popup.value.close()
	}
	
	const showDialog = async (value) => {
		if (value) {
			popup.value && popup.value.open()
		} else {
			onClose()
		}
	}
	
	const queryParam = ref({
		activeId: '',
		type: 1, // 日期类型：1-近1个月，2-今日，3-昨日，4-本周，5-自定义日期
		orderTimeStart: '', // 下单开始时间,格式:yyyy-MM-dd HH:mm:ss
		orderTimeEnd: '' // 下单结束时间,格式:yyyy-MM-dd HH:mm:ss
	})
	
	const changeType = (val) => {
		if (queryParam.value.type === 5) {
			queryParam.value.orderTimeStart = ''
			queryParam.value.orderTimeEnd = ''
		}
		queryParam.value.type = val
	}
	
	const change = (e, type) => {
		if (type === 'start') {
			if (queryParam.value.orderTimeEnd) {
				const diffDay = dayjs(e).diff(queryParam.value.orderTimeEnd, 'day')
				if (Math.abs(diffDay) > 31) {
					uni.showToast({
						icon: 'none',
						title: '时间跨度不能超过31天'
					})
					return
				}
			}
			queryParam.value.orderTimeStart = e
		} else if (type === 'end') {
			if (queryParam.value.orderTimeStart) {
				const diffDay = dayjs(e).diff(queryParam.value.orderTimeStart, 'day')
				if (Math.abs(diffDay) > 31) {
					uni.showToast({
						icon: 'none',
						title: '时间跨度不能超过31天'
					})
					return
				}
			}
			queryParam.value.orderTimeEnd = e
		}
		if (queryParam.value.orderTimeStart || queryParam.value.orderTimeEnd) {
			queryParam.value.type = 5
		}
	}
	
	const query = () => {
		queryParam.value.activeId = props.id
		if (queryParam.value.type === 5) {
			if (!queryParam.value.orderTimeStart) {
				uni.showToast({
					icon: 'none',
					title: '请选择开始时间'
				})
				return
			} else if (!queryParam.value.orderTimeEnd) {
				uni.showToast({
					icon: 'none',
					title: '请选择结束时间'
				})
				return
			}
		}
		preExportApi({
			checkState: 0, // checkState 预检查标识:0-需要，1-不需要
			...queryParam.value
		}).then(() => {
			toExport(exportOrderUrl({
				checkState: 1, // checkState 预检查标识:0-需要，1-不需要
				...queryParam.value
			}))
		})
	}
	
	const fillZero = (val) => {
		return val < 10 ? `0${val}` : val
	}
	
	// 订单导出格式：订单yyyyMMddHHmmss格式的时间+6位随机数
	const createFileName = () => {
		const now = new Date()
		const randomNum = ('000000' + Math.floor(Math.random() * 999999)).slice(-6)
		return `订单${now.getFullYear()}${fillZero(now.getMonth()+1)}${fillZero(now.getDate())}${fillZero(now.getHours())}${fillZero(now.getMinutes())}${fillZero(now.getSeconds())}${randomNum}.xlsx`
	}
	
	const toExport = async (url) => {
		const token = uni.getStorageSync('token')
		uni.downloadFile({
			url,
			header: {
				Authorization: token
			},
			success(res) {
				uni.shareFileMessage({
					filePath: res.tempFilePath,
					fileName: createFileName(),
					success() {
						onClose()
					},
					fail(err) {
						uni.showToast({
							icon: 'none',
							title: err && err.errMsg || '文件分享失败'
						})
					}
				})
			},
			fail(err) {
				uni.showToast({
					icon: 'none',
					title: err && err.errMsg || '文件下载失败'
				})
			}
		})
	}
	
	defineExpose({
		showDialog
	})
</script>
